package com.tsoj.tsojjudgeservice.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.tsoj.model.codesandbox.JudgeInfo;
import com.tsoj.model.dto.question.JudgeCase;
import com.tsoj.model.dto.question.JudgeConfig;
import com.tsoj.model.enums.JudgeInfoMessageEnum;
import com.tsoj.model.po.Question;
import com.tsoj.model.po.QuestionSubmit;


import java.util.List;

public class JavaJudgeStrategy implements JudgeStrategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Long memory = judgeInfo.getMemory();
        Long time = judgeInfo.getTime();
        String message = judgeInfo.getMessage();
        //输入输出
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        QuestionSubmit questionSubmit = judgeContext.getQuestionSubmit();
        //封装返回类
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setTime(time);
        judgeInfoResponse.setMemory(memory);
        //判断沙箱执行结果与预期的是否一致
        if(outputList.size() != inputList.size()){
            JudgeInfoMessageEnum wrongAnswer = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfo.setMessage(wrongAnswer.getValue());
            return judgeInfo; 
        }
        
        //单个判断
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if(!judgeCase.getOutput().equals(outputList.get(i))){
                JudgeInfoMessageEnum wrongAnswer = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfo.setMessage(wrongAnswer.getValue());
                return judgeInfo;
            }
        }

        //判断输出堆栈和时间是否超出
        String judeconfig = question.getJudgeconfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judeconfig, JudgeConfig.class);
        if(memory > judgeConfig.getMemoryLimit()){
            JudgeInfoMessageEnum memoryLimitExceeded = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfo.setMessage(memoryLimitExceeded.getValue());
            return judgeInfo;
        }
        //java启动需要10秒
        long JAVA_PROGRAM_TIME_COST = 10000L;
        if((time - JAVA_PROGRAM_TIME_COST) > judgeConfig.getTimeLimit()){
            JudgeInfoMessageEnum timeLimitExceeded = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(timeLimitExceeded.getValue());
            return judgeInfoResponse;
        }
        JudgeInfoMessageEnum accepted = JudgeInfoMessageEnum.ACCEPTED;
        judgeInfoResponse.setMessage(accepted.getValue());
        return judgeInfoResponse;
    }
}
